package org.cybzacg.convert.converters.date;


import lombok.extern.slf4j.Slf4j;
import org.cybzacg.convert.annotation.Converter;
import org.cybzacg.convert.context.ConversionContext;
import org.cybzacg.convert.enums.ConversionPriority;
import org.cybzacg.convert.enums.ConversionType;

import java.time.*;
import java.time.format.DateTimeFormatter;

/**
 * LocalDate转换器
 * 专门处理LocalDate类型的转换
 *
 * @author cybzacg.blog
 * @version 4.0
 * @since 3.0
 */
@Slf4j
@Converter(
    name = "LocalDateConverter",
    priority = ConversionPriority.MEDIUM_HIGH,
    description = "LocalDate转换器，专门处理LocalDate类型的转换",
    enabled = true,
    version = "4.0",
    author = "cybzacg.blog",
    supportedTypes = {LocalDate.class},
    tags = {"localdate", "date", "datetime", "conversion"}
)
public class LocalDateConverter extends AbstractDateTimeConverter<LocalDate> {

    public LocalDateConverter() {
        super(LocalDate.class, ConversionPriority.MEDIUM_HIGH);
    }

    @Override
    protected ConversionType getConversionType() {
        return ConversionType.LOCAL_DATE;
    }

    @Override
    protected LocalDate parseFromString(String str, DateTimeFormatter formatter) {
        return LocalDate.parse(str, formatter);
    }

    @Override
    protected LocalDate convertFromInstant(java.time.Instant instant, ConversionContext context) {
        return instant.atZone(DEFAULT_ZONE_ID).toLocalDate();
    }

    @Override
    protected String[] getSupportedPatterns() {
        return org.cybzacg.convert.constants.DateFormats.DATE_FORMAT_PATTERNS;
    }

    @Override
    protected LocalDate convertFromOtherDateTime(Object source, ConversionContext context) {
        // LocalDateTime转换
        if (source instanceof LocalDateTime localDateTime) {
            return localDateTime.toLocalDate();
        }

        // ZonedDateTime转换
        if (source instanceof ZonedDateTime zonedDateTime) {
            return zonedDateTime.toLocalDate();
        }

        // Year转换
        if (source instanceof Year year) {
            return year.atDay(1);
        }

        // YearMonth转换
        if (source instanceof YearMonth yearMonth) {
            return yearMonth.atDay(1);
        }

        return null;
    }

    @Override
    protected LocalDate getDefaultValue() {
        return org.cybzacg.convert.constants.DateTimeDefaults.LOCAL_DATE_DEFAULT;
    }
}
